package com.utils.basehelper.encrypt;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

public class HttpHelper {
	
	/**
	 * 将post请求体解析出来
	 * @param request
	 * @return
	 */
	public static String parsePost(HttpServletRequest request) {
		InputStream in = null;
		String body = null;
		try {
			in = request.getInputStream();
			body = InputStreamToString(in, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return body;
	}
	
	/**
	 * 请求流转化为字符串
	 * @param inputStream
	 * @param unicode 编码格式
	 * @return
	 */
	public static String InputStreamToString(InputStream inputStream, String unicode) {
		final int bufferSize = 1024;
		final char[] buffer = new char[bufferSize];
		final StringBuilder out = new StringBuilder();
		Reader in;
		try {
			in = new InputStreamReader(inputStream, unicode);
			for (;;) {
				int rsz = in.read(buffer, 0, buffer.length);
				if (rsz < 0)
					break;
				out.append(buffer, 0, rsz);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toString();
	}
	
	/**
	 * 根据域名、URI、参数集合拼接URL
	 * @param domain
	 * @param uri
	 * @param param
	 * @return
	 */
	public static String getUrl(String domain, String uri, Map<String, String> param) {
		if(param==null||param.size()<=0)
			return null;
		StringBuffer sb = new StringBuffer();
		sb.append(domain);
		sb.append(uri);
		sb.append("?");
		for (Entry<String, String> entry : param.entrySet()) {
			if(StringUtils.isNotBlank(entry.getValue())) {
				sb.append(entry.getKey());
				sb.append("=");
				sb.append(entry.getValue());
				sb.append("&");
			}
		}
		String url = sb.toString();
		if(url.endsWith("&"))
			url = url.substring(0,url.length()-1);
		return url;
	}
	
    public static final String decodeURL(String param){
        if(param == null) return null;
        try{
            return URLDecoder.decode(param,"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static final String encodeURL(String param){
        if(param == null) return null;
        try{
            return URLEncoder.encode(param,"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static final String decodeAndToUpperCase(String param){
        String ret  = HttpHelper.decodeURL(param);
        ret = ret==null?"":ret.toUpperCase();
        return ret;
    }
	
}
